﻿@model Fap.AspNetCore.ViewModel.FormViewModel

<title>
    <fap-multilang lang-key="profile" default-content="个人资料"></fap-multilang>
</title>


<div class="row">
    <div class="col-xs-12">
        <div class="col-xs-12 col-sm-4 center">
            <div>
                <h5 class="blue">
                    <i class="ace-icon fa fa-hand-o-down icon-animated-hand-pointer orange"></i>
                    <fap-multilang lang-key="click_image_to_edit" default-content="点击图片可以编辑"></fap-multilang>
                </h5>

                <!-- #section:pages/profile.picture -->
                <span class="profile-picture">
                    <img id="avatar" data-pk="@_applicationContext.EmpPhoto" style="width:160px;" class="editable img-responsive" alt="@_applicationContext.EmpName" src="@Url.Content("~/Component/Photo"+"/"+_applicationContext.EmpPhoto)" />
                </span>

                <!-- /section:pages/profile.picture -->
                <div class="space-4"></div>

                <div class="width-80 label label-info label-xlg arrowed-in arrowed-in-right">
                    <div class="inline position-relative">
                        <a href="#" class="user-title-label dropdown-toggle" data-toggle="dropdown">
                            <i class="ace-icon fa fa-circle light-green"></i>
                            &nbsp;
                            <span class="white">@_applicationContext.EmpName</span>
                        </a>

                    </div>
                </div>
            </div>

            <div class="space-6"></div>
            <div class="profile-contact-links">
                <a href="javascript:void(0)" id="btnModifyProfile" class="btn btn-link">
                    <i class="ace-icon fa fa-pencil bigger-120 green"></i>
                    修改个人信息
                </a>

                <a href="javascript:void(0)" id="btnSubInfo" class="btn btn-link">
                    <i class="ace-icon fa fa-envelope bigger-120 pink"></i>
                    附属信息
                </a>

                <a href="javascript:void(0)" id="btnJobSummary" data-title="@ViewBag.Titles" class="btn btn-link">
                    <i class="ace-icon fa fa-globe bigger-125 blue"></i>
                    职位说明
                </a>
            </div>
        </div>

        <div class="col-xs-12 col-sm-8">
            <div class="widget-box transparent">
                <div class="widget-body">
                    <div class="widget-main padding-2">
                        <div id="profile-info-1" class="profile-info">
                            <fap-form form-model="Model"></fap-form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script type="text/javascript">
    var scripts = [null, "/Scripts/Workflow/business.js", null]
    $('.page-content-area').ace_ajax('loadScripts', scripts, function () {
        //inline scripts related to this page
        jQuery(function ($) {
            // *** editable avatar *** //
            try {//ie8 throws some harmless exceptions, so let's catch'em
                $.fn.editable.defaults.mode = 'inline';
                //first let's add a fake appendChild method for Image element for browsers that have a problem with this
                //because editable plugin calls appendChild, and it causes errors on IE at unpredicted points
                try {
                    document.createElement('IMG').appendChild(document.createElement('B'));
                } catch (e) {
                    Image.prototype.appendChild = function (el) { }
                }

                var last_gritter
                $('#avatar').editable({
                    type: 'image',
                    name: 'avatar',
                    value: null,
                    image: {
                        //specify ace file input plugin's options here
                        btn_choose: $.lang("chang_photo", "更换照片"),
                        droppable: true,
                        maxSize: 11000000,//~100Kb

                        //and a few extra ones here
                        name: 'avatar',//put the field name here as well, will be used inside the custom plugin
                        on_error: function (error_type) {//on_error function will be called when the selected file has a problem
                            if (last_gritter) $.gritter.remove(last_gritter);
                            if (error_type == 1) {//file format error
                                last_gritter = $.gritter.add({
                                    title: $.lang("file_not_image", "文件不是图片") + '!',
                                    text: $.lang("please_select", "请选择") + 'jpg|gif|png image!',
                                    class_name: 'gritter-error gritter-center'
                                });
                            } else if (error_type == 2) {//file size rror
                                last_gritter = $.gritter.add({
                                    title: $.lang("filesize_too_max", "文件太大") + '!',
                                    text: $.lang("filesize_not_exceed", "文件大小不要超过") + '10M!',
                                    class_name: 'gritter-error gritter-center'
                                });
                            }
                            else {//other error
                            }
                        },
                        on_success: function () {
                            $.gritter.removeAll();
                        }
                    },
                    url: function (params) {
                        // ***UPDATE AVATAR HERE*** //
                        //for a working upload example you can replace the contents of this function with
                        //examples/profile-avatar-update.js
                        var submit_url = "@Url.Content("~/Component/UploadFile/")@_applicationContext.EmpPhoto";//please modify submit_url accordingly
                        var deferred = null;
                        var avatar = '#avatar';

                        //if value is empty (""), it means no valid files were selected
                        //but it may still be submitted by x-editable plugin
                        //because "" (empty string) is different from previous non-empty value whatever it was
                        //so we return just here to prevent problems
                        var value = $(avatar).next().find('input[type=hidden]:eq(0)').val();
                        if (!value || value.length == 0) {
                            deferred = new $.Deferred
                            deferred.resolve();
                            return deferred.promise();
                        }

                        var $form = $(avatar).next().find('.editableform:eq(0)')
                        var file_input = $form.find('input[type=file]:eq(0)');
                        var pk = $(avatar).attr('data-pk');//primary key to be sent to server

                        var ie_timeout = null

                        if ("FormData" in window) {
                            var formData_object = new FormData();//create empty FormData object

                            //serialize our form (which excludes file inputs)
                            $.each($form.serializeArray(), function (i, item) {
                                //add them one by one to our FormData
                                formData_object.append(item.name, item.value);
                            });
                            //and then add files
                            $form.find('input[type=file]').each(function () {
                                var field_name = $(this).attr('name');
                                var files = $(this).data('ace_input_files');
                                if (files && files.length > 0) {
                                    formData_object.append(field_name, files[0]);
                                }
                            });

                            //append primary key to our formData
                            formData_object.append('pk', pk);

                            deferred = $.ajax({
                                url: submit_url,
                                type: 'POST',
                                processData: false,//important
                                contentType: false,//important
                                dataType: 'json',//server response type
                                data: formData_object
                            })
                        }
                        else {
                            deferred = new $.Deferred

                            var temporary_iframe_id = 'temporary-iframe-' + (new Date()).getTime() + '-' + (parseInt(Math.random() * 1000));
                            var temp_iframe =
									$('<iframe id="' + temporary_iframe_id + '" name="' + temporary_iframe_id + '" \
									frameborder="0" width="0" height="0" src="about:blank"\
									style="position:absolute; z-index:-1; visibility: hidden;"></iframe>')
									.insertAfter($form);

                            $form.append('<input type="hidden" name="temporary-iframe-id" value="' + temporary_iframe_id + '" />');

                            //append primary key (pk) to our form
                            $('<input type="hidden" name="pk" />').val(pk).appendTo($form);

                            temp_iframe.data('deferrer', deferred);
                            //we save the deferred object to the iframe and in our server side response
                            //we use "temporary-iframe-id" to access iframe and its deferred object

                            $form.attr({
                                action: submit_url,
                                method: 'POST',
                                enctype: 'multipart/form-data',
                                target: temporary_iframe_id //important
                            });

                            $form.get(0).submit();
                            //if we don't receive any response after 30 seconds, declare it as failed!
                            ie_timeout = setTimeout(function () {
                                ie_timeout = null;
                                temp_iframe.attr('src', 'about:blank').remove();
                                deferred.reject({ 'status': 'fail', 'message': 'Timeout!' });
                            }, 30000);
                        }
                        //deferred callbacks, triggered by both ajax and iframe solution
                        deferred
						.done(function (result) {//success
						    var res = result[0];//the `result` is formatted by your server side response and is arbitrary
						    if (res == '1') {
						        //$(avatar).get(0).src = "~/Content/avatars/profile-pic.jpg";
						        $(avatar).get(0).src = $.randomUrl("@Url.Content("~/Component/Photo/"+_applicationContext.EmpPhoto)");
						        if (last_gritter) $.gritter.remove(last_gritter);
						        last_gritter = $.gritter.add({
						            title: $.lang("photo_updated", "照片已更新") + '!',
						            text: '',
						            class_name: 'gritter-info gritter-center'
						        });
						    }
						    //else alert(res.message);
						})
						.fail(function (result) {//failure
						    alert($.lang("update_error", "更新图片遇到错误"));
						})
						.always(function () {//called on both success and failure
						    if (ie_timeout) clearTimeout(ie_timeout)
						    ie_timeout = null;
						});

                        return deferred.promise();
                        // ***END OF UPDATE AVATAR HERE*** //

                        return deferred.promise();

                        // ***END OF UPDATE AVATAR HERE*** //
                    },

                    success: function (response, newValue) {
                        $(avatar).get(0).src = $.randomUrl("@Url.Content("~/Component/Photo/"+_applicationContext.EmpPhoto)");
                    }
                })
            } catch (e) { }
            /////////////////////////////////////
            $(document).one('ajaxloadstart.page', function (e) {

            });
            $('#profile-info-1').ace_scroll({
                size:600,
                mouseWheelLock: true,
                alwaysVisible: true
            });

            $("#btnModifyProfile").on(ace.click_event, function () {
                applyBusiness('702824364243943424', "个人信息修改");
            })
            $("#btnSubInfo").on(ace.click_event, function () {
                var dialog = bootbox.dialog({
                    title: "附属信息",
                    size: 'large',
                    message: '<p><i class="fa fa-spin fa-spinner"></i> Loading...</p>',
                    buttons: {
                        cancel: {
                            label: "关闭", className: "btn-default"
                        }
                    }
                });
                var data = { "gridViews": @Html.Raw(ViewBag.SubInfo)};              
                dialog.init(function () {
                    var url = "@Html.Raw(Url.Action("MultiDataGrid", "Component", new { area = "" }))" + "?menuUrl=~/Employee/Manage/Profile";
                    $.post(url, data, function (ev) {
                        dialog.find('.bootbox-body').html(ev);
                    })
                });
            })
            $("#btnJobSummary").on(ace.click_event, function () {
                var title = $(this).data("title");
                if (title) {
                    bootboxWindow($.lang("summary", "说明书"), basePath + "/Organization/OrgDept/TitleOutline", null, { fids: title });
                } else {
                    $.msg("无职位头衔，无法查看");
                }
            })
        });
    })
</script>
